#!/usr/bin/env python
#-*-coding=utf8-*-


import optparse
import sys
import os

_STRING = '' #search string 

def search_file(path,_recursive=False,search_fname=False):
    d = os.listdir(path)
    for fd in d:
        _fd = os.path.join(path,fd)
        if search_fname and search_fname in fd:
            print get_color(os.path.abspath(_fd),search_fname)
        if _STRING:
            if os.path.isfile(_fd):
                check_file(_fd)
        if _recursive and os.path.isdir(_fd):
            #recursive search files
            search_file(_fd,_recursive,search_fname)
                

def check_file(f,search_str=''):
    
    if not search_str:
        if not _STRING:
            return
        search_str = _STRING
    with open(f,'r') as fobj:
        line_no = 0
        for line in fobj:
            line_no += 1
            #if the length of one line larger than 300
            #will ignoe this line
            if len(line) > 300:
                continue
            if search_str in line:
                print os.path.abspath(f),line_no,
                print get_color(line,_STRING),

def get_color(msg,hlight_str):
    """just for linux"""
    _lst = msg.split(hlight_str)
    new_str = '\033[1;35;40m%s\033[0m'%hlight_str
    return new_str.join(_lst)

def main():
    parser = optparse.OptionParser()
    parser.add_option('-r','--recursive',
            action='store_true',
            default=False,
            dest='recursive',
            help="search files recursive."
            )
    parser.add_option('-d',
            action='store',
            default='.',
            dest='directory',
            help='the directory that search for,default is current directory.')
    parser.add_option('-s',
            action='store',
            dest='search_string',
            help='the string you want to search in files.')
    parser.add_option('-n','--name',
            action='store',
            dest='file_name',
            help='the file name string you searched.')

    args = sys.argv[1:]
    if not args:
        args = ['-h']
    opts,remain =  parser.parse_args(args)
    global _STRING
    _STRING = opts.search_string
    _file_name = opts.file_name
    if not _STRING and not _file_name:
        print 'must provide search string or file name'
        exit()
    
    search_file(opts.directory,opts.recursive,_file_name)

if __name__ == "__main__":
    main()
